package booksys.bod;

import booksys.common.CurrentUser;
import booksys.common.Result;
import booksys.common.Utils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet({
        "/bod/bodList",
        "/bod/bodDoAdd"
})//注解配置访问地址 / 发送地址
public class BodAPI extends HttpServlet {
    private static final Logger logger = LogManager.getLogger(BodAPI.class);//日志输出

    // 客户端（浏览器）发送数据的方式有多种: get, post, delete, put ...

    /**
     * 负责接收客户端发来的post请求
     *
     * @param request  客户端发来的请求
     * @param response 负责向客户端响应
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        BodService bodService = new BodService();
        String path = request.getServletPath();
        CurrentUser currentUser = (CurrentUser) request.getSession().getAttribute(CurrentUser.SESSION_ATTR_NAME);

        if ("/bod/bodDoAdd".equals(path)) {
            try {
                BodcardDto dto = Utils.getBeanFromRequest(BodcardDto.class, request);

                bodService.addBodcard(dto, currentUser.getUserId());

                Utils.outJson(response, Result.success());
            } catch (Exception e) {
                e.printStackTrace();
                Utils.outJson(response, Result.fail(Result.ERR_CODE_BUSINESS, e.getMessage()));
            }
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        //创建业务模型对象（服务对象/Service对象），通过业务对象执行业务方法
        BodService bodService = new BodService();
        CurrentUser currentUser = (CurrentUser) request.getSession().getAttribute(CurrentUser.SESSION_ATTR_NAME);

        String path = request.getServletPath();
        if ("/bod/bodList".equals(path)) {
            try {
                List<Bodcard> bodcardList = bodService.getNewBodcardList(currentUser);

                Utils.outJson(response, Result.success(bodcardList));

                Utils.outResult(response, Result.success(bodcardList));
            } catch (IOException e) {
                e.printStackTrace();
                Utils.outJson(response, Result.fail(Result.ERR_CODE_BUSINESS, e.getMessage()));
            }
        }

    }
}

